package com.project806.Module;

import android.util.Log;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.project806.Util.CleanDataUtils;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.utils.UrlSafeBase64;

import org.json.JSONException;
import org.json.JSONObject;

import javax.annotation.Nonnull;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class UploadModule extends ReactContextBaseJavaModule {

    //七牛后台的key
    private String AccessKey;
    //七牛后台的secret
    private String SecretKey;

    private String BucketName = "laijia";

    private final String BASE_URL = "http://pzszknxow.bkt.clouddn.com/";
    private final String MAC_NAME = "HmacSHA1";
    private final String ENCODING = "UTF-8";

    private Configuration configuration;

    private UploadManager uploadManager;

    private static long delayTimes = 3029414400l; //有效时间

    public UploadModule(@Nonnull ReactApplicationContext reactContext) {
        super(reactContext);
        init();
    }

    private void init() {
        AccessKey = "Gc8saASBVoN1NZFDaH6QkGaYGcf1JhVM8MT63cn2";
        SecretKey = "UrVwVAx9ScPq7vHY8XH_wvHFXkcsaVvkEhWPxzyt";
        configuration = new Configuration.Builder()
                .zone(FixedZone.zone2)
                .build();
        uploadManager = new UploadManager(configuration);
    }

    @Nonnull
    @Override
    public String getName() {
        return "UploadModule";
    }

    @ReactMethod
//    public void uploadVideo(String filePath, Callback successCallback, Callback errorCallback, Callback progressCallback) throws Exception {
    public void uploadVideo(String filePath, Callback successCallback, Callback errorCallback) throws Exception {

        String token = getToken();
        uploadManager.put(filePath, null, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {
                            try {
                                String name = info.response.getString("key");
//                                Log.d("ReactNativeJS", BASE_URL + name);
                                successCallback.invoke(BASE_URL + name);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
//                            Log.d("ReactNativeJS", "上传失败");
                            errorCallback.invoke("上传失败");
                        }
                    }
                }, new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            public void progress(String key, double percent) {
//                                progressCallback.invoke(percent + "");
                            }
                        }, null));
    }

    //获取七牛token
    private String getToken() {
        String token = "";
        try {
            // 1 构造上传策略
            JSONObject _json = new JSONObject();
            long _dataline = System.currentTimeMillis() / 1000 + 3600;
            _json.put("deadline", _dataline);// 有效时间为一个小时
            _json.put("scope", BucketName);//七牛空间名
            String _encodedPutPolicy = UrlSafeBase64.encodeToString(_json.toString().getBytes());
            byte[] _sign = HmacSHA1Encrypt(_encodedPutPolicy, SecretKey);
            String _encodedSign = UrlSafeBase64.encodeToString(_sign);
            Log.d("xxxx", _encodedSign);
            token = AccessKey + ':' + _encodedSign + ':' + _encodedPutPolicy;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * @param encryptText 被签名的字符串
     * @param encryptKey  密钥
     * @return
     * @throws Exception
     */
    public byte[] HmacSHA1Encrypt(String encryptText, String encryptKey)
            throws Exception {
        byte[] data = encryptKey.getBytes(ENCODING);
        // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        // 生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance(MAC_NAME);
        // 用给定密钥初始化 Mac 对象
        mac.init(secretKey);
        byte[] text = encryptText.getBytes(ENCODING);
        // 完成 Mac 操作
        return mac.doFinal(text);
    }
}
